package com.xinxing.learning.datasource.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 第一个数据源的mybatis-plus配置
 * 定义SqlSessionFactoryBean
 * 配置扫描mapper的路径，entity的Alias的路径，xml文件路径
 */
@Configuration
@MapperScan(basePackages = {"com.xinxing.learning.datasource.mapper.first"}, sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstMybatisConfig {

    @Bean("firstSqlSessionFactory")
    public SqlSessionFactory masterSqlSessionFactory(@Qualifier("first") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        // 1、添加数据源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 2、xml配置文件
        PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        String localMapperXmlPattern = "classpath*:/mapper/first/*.xml";
        sqlSessionFactoryBean.setMapperLocations(resourcePatternResolver.getResources(localMapperXmlPattern));
        // 3、实体类别名
        String typeAliasesPackage = "com.xinxing.learning.datasource.entity";
        sqlSessionFactoryBean.setTypeAliasesPackage(typeAliasesPackage);
        // 4、mybatis其他的属性配置
        MybatisConfiguration configuration = new MybatisConfiguration();
        // 4.1、配置日志实现
        configuration.setLogImpl(StdOutImpl.class);
        // 4.2、此处可以添加其他mybatis配置 例如转驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }
}
